import { createLogger } from '../modules/Logger.js';
import fs from 'fs';
import yaml from 'yaml';
import { Common, Data, Version } from '../components/index.js';
import Theme from './help/theme.js';
import path from 'path';

const __filename = new URL(import.meta.url).pathname;
const __dirname = path.dirname(__filename);

// 配置文件路径
const CONFIG_PATH = path.resolve(__dirname, '../config/master.yaml');

let masterIds = [];

// 创建日志实例
const logger = createLogger('皮皮权限管理');

try {
  const fileContents = fs.readFileSync(CONFIG_PATH, 'utf8');
  const config = yaml.parse(fileContents);
  masterIds = config.masterIds || [];
} catch (err) {
  logger.error(`加载 ${CONFIG_PATH} 配置失败: ${err.message}`);
}

Bot.GetMaster = async (e) => {
  e.isMaster = masterIds.includes(e.user_id);
};

try {
  Bot.on('message', (e) => { Bot.GetMaster(e); });
  Bot.on('notice.group.ban', (e) => { Bot.GetMaster(e); });
  Bot.on('notice.group.increase', (e) => { Bot.GetMaster(e); });

  if (masterIds.length > 0) {
    const masterListString = masterIds
     .map(id => `            ${id}`)
     .join('\n');
    logger.info(`皮皮权限载入完成: \n****************************************\n*  主人列表：                 *\n${masterListString}\n****************************************`);
  } else {
    logger.info(`皮皮权限载入完成: \n****************************************\n*  主人列表：无       *\n****************************************`);
  }
} catch (err) {
  logger.error(`发生错误: ${err.message}`);
}

export class help extends plugin {
  constructor() {
    super({
      name: '皮皮插件',
      dsc: '皮皮帮助',
      event: 'message',
      priority: 100,
      rule: [
        {
          reg: /^#?(皮皮|pippi)(命令|帮助|菜单|help|说明|功能|指令|使用说明)$/i,
          fnc: 'help',
        },
        {
          reg: /^#?(皮皮|pippi)(版本|版本信息|version(info)?)$/i,
          fnc: 'versionInfo',
        },
      ],
    });
    // 为插件创建日志实例
    this.logger = createLogger(this.name);
  }

  async help(e) {
    try {
      const { diyCfg, sysCfg } = await Data.importCfg('help');

      const helpConfig = {
        ...(sysCfg.helpCfg || {}),
        ...(diyCfg.helpCfg || {}),
      };

      const helpList = diyCfg.helpList || sysCfg.helpList || [];
      const helpGroup = [];

      for (const group of helpList) {
        if (group.auth === 'master' && !e.isMaster) {
          continue;
        }

        for (const help of group.list) {
          const icon = parseInt(help.icon, 10) || 0;
          if (!icon) {
            help.css = 'display:none';
          } else {
            const x = (icon - 1) % 10;
            const y = Math.floor((icon - 1) / 10);
            help.css = `background-position:-${x * 50}px -${y * 50}px`;
          }
        }

        helpGroup.push(group);
      }

      const themeData = await Theme.getThemeData(helpConfig, sysCfg.helpCfg || {});
      return await Common.render(
        'help/index',
        {
          helpCfg: helpConfig,
          helpGroup,
          ...themeData,
          element: 'default',
        },
        { e, scale: 1.2 }
      );
    } catch (error) {
      this.logger.error(`执行 help 方法时发生错误: ${error.message}`);
    }
  }

  async versionInfo(e) {
    try {
      return await Common.render(
        'help/version-info',
        {
          currentVersion: Version.ver,
          changelogs: Version.logs,
          elem: 'cryo',
        },
        { e, scale: 1.2 }
      );
    } catch (error) {
      this.logger.error(`执行 versionInfo 方法时发生错误: ${error.message}`);
    }
  }
}